package com.zhongkeruan.user.controller;

import com.zhongkeruan.common.constants.StatusCode;
import com.zhongkeruan.common.dto.UserDto;
import com.zhongkeruan.common.model.Order;
import com.zhongkeruan.common.model.User;
import com.zhongkeruan.common.utils.JwtUtil;
import com.zhongkeruan.common.utils.SnowFlakeUtil;
import com.zhongkeruan.common.vo.Result;
import com.zhongkeruan.user.hystrix.OrderHystrix;
import com.zhongkeruan.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author yangyao
 * @Description: UserController
 * @date 2019/1/11 15:12
 */
@RestController
@RefreshScope
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderHystrix orderHystrix;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private SnowFlakeUtil snowFlakeUtil;

    @GetMapping
    public Result getUserList() throws Exception{
        List<User> userList = userService.getUserList();
        return new Result(StatusCode.SUCCESS,"查询成功", userList);
    }

    @RequestMapping("/{id}")
    public Result getUserById(@PathVariable("id") Long id) throws Exception{
        User user = userService.getUserById(id);
        return new Result(StatusCode.SUCCESS,"查询成功", user);
    }

    /**
     * 断路器超时设置
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/{userId}/orders")
    public Result getOrderInfoByUserId(@PathVariable("userId") Long userId) throws Exception{
        Result orderListResult= orderHystrix.getOrderListByUserId(userId);
        User user = userService.getUserById(userId);
        List<Order> orderList = (List<Order>) orderListResult.getData();
        UserDto userDto = new UserDto();
        userDto.setUser(user);
        userDto.setOrders(orderList);
        return new Result(StatusCode.SUCCESS,"查询成功",userDto);
    }

    /**
     * 这个接口接口不规范，演示用
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/order-hystrix/{userId}")
    public Result getOrderHystricInfoByUserId(@PathVariable("userId") Long userId,HttpServletRequest request) throws Exception{
        String token = request.getHeader("access_token");
        Result result = orderHystrix.getOrderListByUserId(userId);
        return result;
    }

    /**
     * 登录
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/login")
    public Result login(@RequestBody User user) throws Exception{
        User loginUser = userService.findByUserName(user.getUserName());
        if (loginUser == null){
           return new Result(StatusCode.ERROR,"登录失败",null);
        }
        String token = jwtUtil.createToken(String.valueOf(loginUser.getId()), loginUser.getUserName(), "admin");
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("access_token",token);
        map.put("role","admin");
        return new Result(StatusCode.SUCCESS,"登录成功",map);
    }
    @Value("${selfDefineDesc.key}")
    private String selfDefineDesc;

    @GetMapping(value = "/get")
    public String getConfigInfo(){
        return selfDefineDesc;
    }

    /**
     * 测试分布式事务接口
     * @return
     * @throws Exception
     */
    @PostMapping
    public Result addUserAndOrder() throws Exception{
        User user = new User();
        //user.setId(snowFlakeUtil.nextId());
        user.setPassword("111");
        user.setSalt("111");
        user.setState("1");
        user.setUserName(UUID.randomUUID().toString().substring(0,10));
        int result = userService.addUser(user);
        return new Result(StatusCode.SUCCESS,"新增成功");
    }

}
